package com.douyang.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douyang.base.expcetion.VideoException;
import com.douyang.base.model.PageResult;
import com.douyang.base.model.Result;
import com.douyang.base.model.UserBaseInfo;
import com.douyang.base.utils.IdWorkerUtils;
import com.douyang.base.utils.UserUtil;
import com.douyang.dto.CreateLiveDTO;
import com.douyang.dto.LiveListDTO;
import com.douyang.mapper.LiveMapper;
import com.douyang.pojo.Live;
import com.douyang.service.LiveService;
import com.douyang.vo.GetChannelKeyVO;
import com.douyang.vo.LiveGoVO;
import com.douyang.vo.LiveListVO;
import com.douyang.vo.LiveVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2025-03-07
 */
@Service
public class LiveServiceImpl extends ServiceImpl<LiveMapper, Live> implements LiveService {
    @Value("${liveGo.workUrl}")
    private String liveGoWorkUrl;

    @Autowired
    RestTemplate restTemplate;

    @Override
    public Result<LiveVO> getLive() {
        UserBaseInfo loginUserBaseInfo = UserUtil.getLoginUserBaseInfo();

        Live live = lambdaQuery()
                .eq(Live::getPresenterId, loginUserBaseInfo.getId())
                .one();

        if(live == null){
            Result<LiveVO> result=new Result<>();
            result.setCode(404);
            result.setMsg("无直播间");
            return result;
        }

        LiveVO liveVO=new LiveVO();
        BeanUtils.copyProperties(live,liveVO);
        return Result.success(liveVO);

    }

    @Override
    public String createLive(CreateLiveDTO createLiveDTO) {
        UserBaseInfo loginUserBaseInfo = UserUtil.getLoginUserBaseInfo();
        remove(new LambdaQueryWrapper<Live>()
                .eq(Live::getPresenterId, loginUserBaseInfo.getId())
        );

        if(StringUtils.isEmpty(createLiveDTO.getTitle()) || StringUtils.isEmpty(createLiveDTO.getAppName())){
            throw new VideoException("参数缺失");
        }


        ResponseEntity<LiveGoVO> response = restTemplate.exchange(
                liveGoWorkUrl + "/control/get?room={appName}",
                HttpMethod.GET,
                null,
                LiveGoVO.class,
                Map.of("appName", createLiveDTO.getAppName())
        );

        if(!response.getStatusCode().is2xxSuccessful() || response.getBody()==null || response.getBody().getStatus()!=200 || response.getBody().getData()==null){
            throw new VideoException("获取失败，请尝试");
        }
        Live live=Live.builder()
                .title(createLiveDTO.getTitle())
                .appName(createLiveDTO.getAppName())
                .channelKey(response.getBody().getData())
                .presenterAvatar(loginUserBaseInfo.getAvatar())
                .presenterName(loginUserBaseInfo.getUserName())
                .presenterId(loginUserBaseInfo.getId())
                .liveImgUrl(createLiveDTO.getLiveImgUrl())
                .createTime(LocalDateTime.now())
                .build();

        save(live);

        return live.getChannelKey();
    }

    @Override
    public String getAppName() {

        return IdWorkerUtils.getInstance().createUUID();
    }

    @Override
    public void stopLive() {
        UserBaseInfo loginUserBaseInfo = UserUtil.getLoginUserBaseInfo();
        Live live = lambdaQuery().eq(Live::getPresenterId, loginUserBaseInfo.getId()).one();
        if(live!=null){
            removeById(live);
            try {
                restTemplate.exchange(
                        liveGoWorkUrl + "/control/delete?room={appName}",
                        HttpMethod.GET,
                        null,
                        LiveGoVO.class,
                        Map.of("appName",live.getAppName())
                );
            }catch (Exception e){
                e.printStackTrace();
            }

        }



    }
    @Override
    public PageResult<LiveListVO> getLiveList(LiveListDTO liveListDTO) {
        Page<Live> page = lambdaQuery().page(liveListDTO.getPage());


        return PageResult.of(page,live -> {
            LiveListVO liveVO=new LiveListVO();
            BeanUtils.copyProperties(live,liveVO);
            liveVO.setAppName(null);
            return liveVO;
        });
    }

    @Override
    public LiveVO getLiveById(Long presenterId) {
        if(presenterId==null){throw new VideoException("参数异常");}
        Live live = lambdaQuery().eq(Live::getPresenterId, presenterId).one();
        if(live==null){throw new VideoException("该主播不存在或未开播");}
        LiveVO liveVO=new LiveVO();
        BeanUtils.copyProperties(live,liveVO);
        liveVO.setAppName(null);
        return liveVO;

    }
}
